package net.cz.wc.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import net.cz.wc.data.ResourceManager;
import net.cz.wc.main.Context;

public class SingleMetricConnectedDAO extends AbstractDAO {

	public SingleMetricConnectedDAO(Connection conn) {
		super(conn);
	}
	
	private List<String> filters = new ArrayList<String>();
	
	private static final String ALL_METRICS_QUERY = "select id_log, metric_time, metric_name, metric_value from metric ";
	private static final String ORDERED = "order by metric_time asc";
	
	private ResultSet allMetricsRST = null;
	private PreparedStatement allMetricsPSTM = null;
	
	/**
	 * Returns all metrics of the database in a ResultSet
	 * @return ResultSet with all metrics
	 * @throws SQLException
	 */
	public ResultSet getSingleMetrics() throws SQLException {
		StringBuilder metricQuery = new StringBuilder(ALL_METRICS_QUERY);
		if (filters.size() > 0) {
			metricQuery.append(" where");
		}
		
		boolean notFirst = false;
		for (String filter : filters) {
			if (notFirst) {
				metricQuery.append(" and");
			}
			metricQuery.append(" ").append(filter);
			notFirst = true;
		}
		
		metricQuery.append(" ").append(ORDERED);
		
		Context.getContext().addDebugMessage("{getSingleMetrics} executing query: " + metricQuery.toString());
		
		allMetricsPSTM = getConnection().prepareStatement(metricQuery.toString());
		allMetricsRST = allMetricsPSTM.executeQuery();
		
		return allMetricsRST;
	}
	
	public void addFilterExpresion(String property, String operator, String value) {
		String where = property + " " + operator + " '" + value + "'";
		filters.add(where);
	}
	
	public void closeDAO() {
		ResourceManager.closeResultSet(allMetricsRST);
		ResourceManager.closePreparedStatement(allMetricsPSTM);
	}
}
